<template>
  <a-card :bordered="false">
    <div class="table-page-search-wrapper">
      <a-form layout="inline" :labelCol="{ style: 'width:80px' }">
        <!-- {{yAxisMin}}/ {{yAxisMax}}/ {{yAxisInterval}} -->
        <a-row :gutter="48">
          <!-- <a-col :xl="6" :lg="7" :md="8" :sm="24">
              <a-form-item label="车间">
                  <j-dict-select-tag type="list" v-model="queryParam.workshopId" dictCode="data_workshop,workshop_name,workshop_id" placeholder="请选择车间" />
              </a-form-item>
          </a-col>
          <a-col :xl="6" :lg="7" :md="8" :sm="24">
              <a-form-item label="工区">
                  <j-dict-select-tag type="list" v-model="queryParam.areaId" dictCode="data_area,area_name,area_id" placeholder="请选择工区" />
              </a-form-item>
          </a-col> -->
          <!-- <a-col :md="6" :sm="24">
            <a-form-item label="采样属性">
              <j-dict-select-tag
                type="list"
                v-model="queryParam.property"
                dictCode="data_property where prop_type = '日报',prop_name,prop_no"
                placeholder="请选择属性名称"
                @change="peopertyChanage"
                :triggerChange="true"
                ref="sltPeoperty"
              />
            </a-form-item>
          </a-col> -->
          <a-col :md="6" :sm="24">
            <a-form-item label="槽号">
              <a-select show-search placeholder="请选择槽号" v-model="queryParam.dataSoltIds">
                <a-select-option v-for="item in slotIdList" :key="item" :value="item">
                  {{ item }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :xl="6" :lg="11" :md="12" :sm="24">
            <a-form-item label="采样范围">
              <a-range-picker v-model="queryParam.startEndDate" />
            </a-form-item>
          </a-col>
          <a-col :md="6" :sm="24">
            <a-form-item label="采样间隔">
              <a-input v-model="queryParam.distanceValue">
                <template #addonAfter>
                  <a-select v-model="queryParam.distanceUnit" style="width: 80px">
                    <a-select-option value="天">天</a-select-option>
                    <a-select-option value="时">时</a-select-option>
                    <a-select-option value="分">分</a-select-option>
                  </a-select>
                </template>
              </a-input>
            </a-form-item>
          </a-col>
          <a-col :md="6" :sm="24">
            <a-form-item label="聚合方式">
              <a-select placeholder="请选择" default-value="平均值" v-model="queryParam.aggregation">
                <a-select-option value="平均值">平均值</a-select-option>
                <a-select-option value="方差">方差</a-select-option>
                <a-select-option value="均方根">均方根</a-select-option>
                <a-select-option value="偏度">偏度</a-select-option>
                <a-select-option value="峭度">峭度</a-select-option>
                <a-select-option value="波形因子">波形因子</a-select-option>
                <a-select-option value="峰值因子">峰值因子</a-select-option>
                <a-select-option value="脉冲因子">脉冲因子</a-select-option>
                <a-select-option value="裕度因子">裕度因子</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :md="6" :sm="24">
            <span class="table-page-search-submitButtons" style="float: 'right', overflow: 'hidden'">
              <a-button type="primary" @click="handleSearch">查询</a-button>
              <a-button style="margin-left: 8px" @click="resetSearchForm">重置</a-button>
              <a-button style="margin-left: 8px" type="primary" @click="showTb" :disabled="this.barData2.length == 0"
                >查看图表</a-button
              >
            </span>
          </a-col>
        </a-row>
      </a-form>
    </div>
    <a-spin :spinning="loading">
      <a-table
        ref="table"
        size="middle"
        bordered
        rowKey="id"
        class="j-table-force-nowrap"
        :scroll="{ x: true, y: 500 }"
        :columns="columns"
        :dataSource="barData2"
        :pagination="ipagination"
        :loading="loading"
        @change="handleTableChange"
      />

      <!-- <a-tabs defaultActiveKey="2"> 
        <a-tab-pane tab="图表" key="1"> 
          <div id="main" :style="{ width: '100%', height: height + 'px' }"></div>
        </a-tab-pane>
        <a-tab-pane tab="数据" key="2">
        
        </a-tab-pane>
      </a-tabs> -->
    </a-spin>
    <a-modal width="90%" v-model="chartVisible" title="图表">
      <template>
        <a-row :gutter="24">
          <a-col :xl="8" :lg="7" :md="8" :sm="24">
            <j-multi-select-tag
              style="width: 100%"
              v-model="selectPropetyList"
              placeholder="请选择属性名称"
              :options="jSelectMultipleOptions"
            >
            </j-multi-select-tag>
          </a-col>
          <a-col :xl="12" :lg="7" :md="8" :sm="24">
            <span style="float: left; overflow: hidden" class="table-page-search-submitButtons">
              <a-button @click="loadTb" type="primary" style="margin-left: 8px">查看图表</a-button>
              <!-- <a-button @click="handleQzfx" type="primary" style="margin-left: 8px">权重分析</a-button> -->
            </span>
          </a-col>
        </a-row>

        <div id="main" :style="{ width: '100%', height: height + 'px' }"></div>
      </template>
      <template slot="footer">
        <a-button @click="onCancel">关闭</a-button>
      </template>
    </a-modal>
  </a-card>
</template>

<script>
import * as echarts from 'echarts'
import 'echarts-liquidfill'
import AreaChartTy from '@/components/chart/AreaChartTy'
import Bar from '@/components/chart/Bar'
import BarMultid from '@/components/chart/BarMultid'
import LineChartMultid from '@/components/chart/LineChartMultid'
import TransferBar from '@/components/chart/TransferBar'
import STable from '@/components/table/'
import ATextarea from 'ant-design-vue/es/input/TextArea'
import AInput from 'ant-design-vue/es/input/Input'
import JMultiSelectTag from '@/components/dict/JMultiSelectTag'
import moment from 'moment'
import axios from 'axios'
import { httpAction, getAction } from '@/api/manage'

export default {
  name: '日报数据采样查询',
  components: {
    AreaChartTy,
    Bar,
    BarMultid,
    LineChartMultid,
    TransferBar,
    AInput,
    ATextarea,
    STable,
    JMultiSelectTag,
  },
  data() {
    return {
      height: document.body.clientHeight - 357,
      slotIdList: [],
      //barData: [],
      barData2: [],
      areaData: [],
      fields: ['电压'],
      dataList: [],
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 12 },
      },
      form: null,
      // 查询参数
      queryParam: {
        property: '', //采样属性
        startDate: '', //
        endDate: '', //
        startEndDate: [],
        distanceValue: '1', //采样间隔
        distanceUnit: '天', //采样间隔单位
        aggregation: '平均值', //聚合方式
        dataSoltIds: '',
      },
      // 表头
      columns: [
        {
          title: '时间',
          dataIndex: 'date',
          width: '200px',
        },
      ],
      // 加载数据方法 必须为 Promise 对象
      loadData: (parameter) => {},
      loading: false,
      selectedRowKeys: [],
      selectedRows: [],
      myChart: null,
      propertyName: '', //属性名称
      dataPropertyList: [],
      jSelectMultipleOptions: [],
      selectPropetyList: '',
      chartVisible: false,
      colorList: [
        'blue',
        '#ff4683',
        '#F5222D',
        '#FA541C',
        '#FAAD14',
        '#13C2C2',
        '#52C41A',
        '#1890FF',
        '#2F54EB',
        '#722ED1',
        '#2f4f4f',
      ],
    }
  },
  created() {
    this.resetSearchForm()
    this.loadDataSlot()
    this.loadDataProperty()
  },
  mounted() {
    const that = this
    window.onresize = () => {
      return (() => {
        that.height = document.body.clientHeight - 357
      })()
    }
  },
  methods: {
    onCancel() {
      this.chartVisible = false
    },
    sortBykey(ary, key) {
      return ary.sort(function (a, b) {
        let x = a[key]
        let y = b[key]
        return x < y ? -1 : x > y ? 1 : 0
      })
    },
    loadDataSlot() {
      getAction('/dataSlot/dataSlot/list', { pageSize: 9999 })
        .then((res) => {
          if (res.success) {
            var dataSource = res.result.records
            for (let i = 0; i < dataSource.length; i++) {
              this.slotIdList.push(dataSource[i].slotId)
            }
          }
        })
        .finally(() => {
          this.loading = false
        })
    },
    handleSearch() {
      console.log('queryParam:', this.queryParam)
      this.loadBarData()
    },
    loadData2(x, y, max, min, before = '', after = '') {
      let data = []
      for (let i = 0; i < 12; i += 1) {
        data.push({
          [x]: `${before}${i + 1}${after}`,
          [y]: Math.floor(Math.random() * max) + min,
        })
      }
      return data
    },
    // 加载数据
    loadBarData() {
      var that = this
      // if (!that.queryParam.property) {
      //   this.$message.warning('请选择采样属性')
      //   return
      // }
      if (that.queryParam.dataSoltIds.length == 0) {
        this.$message.warning('请选择槽号')
        return
      }
      if (that.queryParam.startEndDate) {
        that.queryParam.startDate = moment(that.queryParam.startEndDate[0]).format('YYYY-MM-DD')
        that.queryParam.endDate = moment(that.queryParam.startEndDate[1]).format('YYYY-MM-DD')
      }
      that.fields = [that.queryParam.dataSoltIds]
      var param = Object.assign({}, that.queryParam)
      param.type = 'SSSJ' //实时数据
      param.dataSoltIds = [param.dataSoltIds]

      that.loading = true
      httpAction('/external/hadoop/resample/slotFull', param, 'post')
        .then((res) => {
          if (res.success) {
            if (res.result && res.result.length == 0) {
              this.$message.warning('没有找到符合条件的数据')
              return
            }
            var list = []
            that.barData2 = []

            var data = res.result
            that.barData2 = that.sortBykey(Object.assign(that.barData2, data), 'date')
            that.columns = [
              {
                title: '时间',
                dataIndex: 'date',
                width: '200px',
              },
            ]
            var object = that.barData2[0]
            for (const key in object) {
              if (Object.hasOwnProperty.call(object, key)) {
                const vl = object[key]
                if (key != 'date') {
                  var _title = that.getPropertyText(key)
                  if (_title != '') {
                    that.columns.push({
                      title: _title,
                      dataIndex: key,
                      width: key.length > 5 ? '180px' : '100px',
                    })
                  }
                }
              }
            }
          } else {
            this.$message.warning(res.message)
          }
        })
        .finally(() => {
          that.loading = false
        })

      // this.barData = this.loadData2('x', 'y', 1000, 200)
    },
    showTb() {
      this.chartVisible = true
      this.selectPropetyList = ''
      this.myChart.clear()
    },
    upFixed(num, fix) {
      //向上取整
      // num为原数字，fix是保留的小数位数
      let result = '0'
      if (Number(num) && fix > 0) {
        // 简单的做个判断
        fix = +fix || 2
        num = num + ''
        if (/e/.test(num)) {
          // 如果是包含e字符的数字直接返回
          result = num
        } else if (!/\./.test(num)) {
          // 如果没有小数点
          result = num + `.${Array(fix + 1).join('0')}`
        } else {
          // 如果有小数点
          num = num + `${Array(fix + 1).join('0')}`
          let reg = new RegExp(`-?\\d*\\.\\d{0,${fix}}`)
          let floorStr = reg.exec(num)[0]
          if (+floorStr >= +num) {
            result = floorStr
          } else {
            let floorNumber = +floorStr + +`0.${Array(fix).join('0')}1`
            let point = /\./.test(floorNumber + '') ? '' : '.'
            let floorStr2 = floorNumber + point + `${Array(fix + 1).join('0')}`
            result = reg.exec(floorStr2)[0]
          }
        }
      }
      return result
    },
    resetSearchForm() {
      var that = this
      this.queryParam = {
        property: '', //采样属性
        startDate: moment(new Date()).format('YYYY-MM') + '-01', //
        endDate: moment(new Date()).format('YYYY-MM-DD'), //
        distanceValue: '1',
        distanceUnit: '天',
        aggregation: '平均值',
        //dataSoltIds: '',
      }
      this.$set(that.queryParam, 'startEndDate', [that.queryParam.startDate, that.queryParam.endDate])
    },
    loadTb() {
      var that = this
      var legendData = []
      var legendData2 = []
      var dateList = []
      var sltPropetyList = that.selectPropetyList.split(',')
      var object = that.barData2[0]
      for (const key in object) {
        if (Object.hasOwnProperty.call(object, key)) {
          const vl = object[key]
          if (key != 'date' && sltPropetyList.includes(key)) {
            var title = that.getPropertyText(key)
            var oV = {
              key: key,
              name: title,
              value: [],
            }
            legendData2.push(oV)
            legendData.push(title)
          }
        }
      }
      that.barData2.forEach((object) => {
        dateList.push(object['date'].replace('00:00:00', ''))
        for (const key in object) {
          if (Object.hasOwnProperty.call(object, key)) {
            const element = object[key]
            if (key != 'date' && sltPropetyList.includes(key)) {
              legendData2.find((o) => o.key == key).value.push(element)
            }
          }
        }
      })
      console.log(legendData2)

      var _series = [
        {
          name: '电压',
          type: 'line',
          showSymbol: false,
          itemStyle: {
            color: 'blue',
          },
          data: [1, 2, 3, 4, 5],
        },
      ]
      _series = []
      var _dataAll = []
      legendData2.forEach((object) => {
        _series.push({
          name: object['name'],
          type: 'line',
          showSymbol: false,
          itemStyle: {
            color: that.colorList[Math.random() * 10],
          },
          data: object['value'],
        })
        _dataAll = _dataAll.concat(object['value'])
      })

      var yAxisMin = parseFloat(Math.min.apply(null, _dataAll) - 0.1).toFixed(2)
      var yAxisMax = parseFloat(Math.max.apply(null, _dataAll) + 0.05).toFixed(2) 
      
      that.loadXLTb2('main', '图表', _series, legendData, yAxisMin, yAxisMax, '日期', '值', dateList)
    },
    loadXLTb2(divId, title, _series, legendData, yAxisMin, yAxisMax, xAxisName, yAxisName, dateList) {
      var that = this
      var chartDom = document.getElementById(divId)
      var myChart = echarts.init(chartDom)
      var option = {
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'cross',
          },
          position: function (pt) {
            return [pt[0], '10%']
          },
        },
        title: {
          // left: 'center',
          text: '', // '[ ' + that.modelBase.code + ' ] '+title,
        },
        legend: {
          data: legendData,
        },
        toolbox: {
          show: true,
          feature: {
            dataZoom: {
              yAxisIndex: 'none',
            },
            dataView: { readOnly: false },
            magicType: { type: ['line', 'bar'] },
            restore: {},
            saveAsImage: {},
          },
        },
        grid: { containLabel: true },
        xAxis: {
          name: xAxisName,
          type: 'category',
          boundaryGap: false,
          data: dateList,
          // axisLabel: {
          //     interval: 30, // 显示所有刻度
          //     rotate: 30 // 将刻度旋转30度
          // }
        },
        yAxis: {
          name: yAxisName,
          type: 'value',
          // boundaryGap: [0, '100%'],
          // interval: that.yAxisInterval, //分割刻度
          min: yAxisMin,
          max: yAxisMax,
        },
        // dataZoom: [
        //   {
        //     type: 'inside',
        //     start: 0,
        //     end: 100,
        //   },
        //   {
        //     start: 0,
        //     end: 100,
        //   },
        // ],
        series: _series,
      }

      option && myChart.setOption(option)
      window.onresize = function () {
        setTimeout(function () {
          myChart.resize()
        }, 10)
      }
    },
    peopertyChanage(v) {
      var that = this
      var obj = this.$refs.sltPeoperty.dictOptions.find((o) => o.value == v)
      if (obj) {
        that.propertyName = obj.text
      }
    },
    loadDataProperty() {
      var that = this
      httpAction('/dataProperty/dataProperty/list?status=1&pageSize=99999&propType=实时', {}, 'get')
        .then((res) => {
          if (res.success) {
            that.dataPropertyList = res.result.records
            that.jSelectMultipleOptions = []
            that.dataPropertyList.forEach((element) => {
              that.jSelectMultipleOptions.push({
                text: element.propName,
                value: element.propNo,
              })
            })
          } else {
            this.$message.warning(res.message)
          }
        })
        .finally(() => {})
    },
    getPropertyText(key) {
      if (this.dataPropertyList && this.dataPropertyList.length > 0) {
        let filterList = this.dataPropertyList.filter((item) => item.propNo == key)
        if (filterList.length > 0) {
          return filterList[0].propName
        }
      }
      return ''
    },
  },
  watch: {
    /*
      'selectedRows': function (selectedRows) {
        this.needTotalList = this.needTotalList.map(item => {
          return {
            ...item,
            total: selectedRows.reduce( (sum, val) => {
              return sum + val[item.dataIndex]
            }, 0)
          }
        })
      }
      */
  },
}
</script>